<?php

namespace app\admin\controller\basic;

use app\common\controller\Backend;
use think\Db;
use fast\Tree;
/**
 * 班级列表
 */
class Classes extends Backend
{

    /**
     * @var \app\common\model\Classes
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Classes;
        $ruleList = Db::name("grade_level")->select();
        // 如果查询结果为空，赋值为空数组
        $this->rulelist = is_array($ruleList) ? $ruleList : [];
        $ruledata = [0 => __('None')];
        foreach ($this->rulelist as $k => &$v) {
            $ruledata[$v['id']] = $v['grade_name'];
        }
        $this->view->assign('ruledata', $ruledata);
        $schoolList = Db::name("school")->select();
        // 如果查询结果为空，赋值为空数组
        $this->schoolList = is_array($schoolList)? $schoolList : [];
        $schooldata = [0 => __('None')];
        foreach ($this->schoolList as $k => &$v) {
            $schooldata[$v['id']] = $v['name'];
        }
        $this->view->assign('schooldata', $schooldata);

    }

    /**
     * 查看
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            // 获取请求参数
            $params = $this->request->param();

            $list = $this->model
                ->with('gradelevel')
                ->order($params['sort'] ?? 'id', $params['order'] ?? 'desc')
                ->paginate([
                    'list_rows' => $params['limit'] ?? 10,
                    'page'      => ($params['offset'] / $params['limit'] + 1) ?? 1
                ]);

            // 获取所有班级ID
            $classIds = array_column($list->items(), 'id');

            // 批量查询每个班级的学生人数
            $studentCounts = Db::name('student_classes_relation')
                ->where('classes_id', 'in', $classIds)
                ->group('classes_id')
                ->column('COUNT(DISTINCT student_id) as count', 'classes_id');

            // 批量查询每个班级的老师人数
            $teacherCounts = Db::name('teacher_classes_relation')
                ->where('classes_id', 'in', $classIds)
                ->group('classes_id')
                ->column('COUNT(DISTINCT teacher_id) as count', 'classes_id');

            // 将人数统计添加到班级数据中
            foreach ($list as &$item) {
                $item['student_count'] = $studentCounts[$item['id']] ?? 0;
                $item['teacher_count'] = $teacherCounts[$item['id']] ?? 0;
            }

            $result = [
                "total" => $list->total(),
                "rows"  => $list->items(),
            ];
            return json($result);
        }

        return $this->view->fetch();
    }

    /**
     * 新增
     */
    public function add(){
        if ($this->request->isPost()) {
            $data = $this->request->post('row/a');
            if (empty($data['name']) || empty($data['avatar']) || empty($data['grade_id'])){
                $this->error('参数不能为空');
            }
            $grade_id = $this->model
                ->where('grade_id', $data['grade_id'])
                ->where('name', $data['name'])
                ->select();
            if (!empty($grade_id)) {
                $this->success('班级已存在');
            }
            $this->model->save($data);
            $classID = $this->model->id;
            $param = [
                'text' => $classID,
            ];

            $qrCode = \addons\qrcode\library\Service::qrcode($param);
            
            $qrcodePath = ROOT_PATH . 'public/uploads/qrcode/';
            
            if (!is_dir($qrcodePath)) {
                @mkdir($qrcodePath);
            }

            if (is_really_writable($qrcodePath)) {
                $filePath = $qrcodePath . 'class_' . $classID.'.png';
                $qrCode->saveToFile($filePath);
            }

            $data['qrcode_path'] = '/uploads/qrcode/class_' . $classID . '.png'; 
            $result = $this->model->save($data, ['id' => $classID]);
            if (!$result) {
                $this->error('新增失败');
            }
        }
        return parent::add();
    }
}
